package com.las.bot.cmd.wx;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.las.annotation.WxCmd;
import com.las.bot.dao.WcGroupDao;
import com.las.bot.dao.WcGroupNumDao;
import com.las.cmd.BaseWxCommand;
import com.las.utils.WxCmdUtil;
import com.model.WcGroup;
import com.model.WcGroupNum;
import com.utils.JsonUtils;
import com.utils.worldcup.WorldCupUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@WxCmd
public class WorldCupWxCmd extends BaseWxCommand {

    private Logger logger = LoggerFactory.getLogger(WorldCupWxCmd.class);

    private final String[] allGroup = {"A", "B", "C", "D", "E", "F", "G", "H"};

    @Autowired
    private WcGroupDao groupDao;

    @Autowired
    private WcGroupNumDao groupNumDao;


    @Override
    public void execute(JSONObject msgData, String wxId, String command) throws Exception {
        if (command.startsWith("#16强")) {
            String groupName = command.replaceAll("#16强", "").trim().toUpperCase();
            logger.info("查询16强，组名是：" + groupName);
            List<String> allList = Arrays.asList(allGroup);
            if (!allList.contains(groupName)) {
                WxCmdUtil.sendMsg(wxId,"请在指令后带小组字母");
                return;
            }
            WcGroup group = groupDao.findByGroupName(groupName);
            if (ObjectUtil.isNull(group)) {
                WxCmdUtil.sendMsg(wxId,"数据暂未统计");
                return;
            }
            List<WcGroupNum> groupNums = groupNumDao.findListByGroupName(groupName);
            if (CollectionUtil.isEmpty(groupNums) || groupNums.size() < 4) {
                WxCmdUtil.sendMsg(wxId,"数据暂未统计");
                return;
            }
            String groupAll = group.getGroupAll();
            List<String> groupA = Arrays.asList(groupAll.split(","));
            String groupEvent = group.getGroupEvent();
            Object[] eventA = JsonUtils.getArrayByJson(groupEvent, String.class).toArray();


            Map<String, WcGroupNum> wcGroupNumMap = groupNums.stream().collect(Collectors.toMap(WcGroupNum::getGroupTeam, v -> v));

            List<Double> groupANum1 = Lists.newArrayList();
            groupA.forEach(ga -> {
                AtomicReference<Double> total = new AtomicReference<>(0.0);
                WcGroupNum groupNum = wcGroupNumMap.get(ga);
                total.updateAndGet(v -> v + groupNum.getGroupNum1());
                total.updateAndGet(v -> v + groupNum.getGroupNum2());
                total.updateAndGet(v -> v + groupNum.getGroupNum3());
                total.updateAndGet(v -> v + groupNum.getGroupNum4());
                groupANum1.add(total.get());
            });

            Map<String, String> params = Maps.newHashMap();
            Map<String, Double> sourceMap = Maps.newHashMap();
            String str1 = WorldCupUtils.getInstance().getByGroup("AT", groupName, groupA, eventA, groupANum1);
            String[] sp = str1.split("\\n");
            for (String str : sp) {
                String[] source = str.split("AT");
                String part = source[0].trim();
                String gv = source[1].trim();
                String gvStr = gv.replaceAll("概率：", "");
                params.put(part, gvStr);
            }

            List<Double> groupANum2 = Lists.newArrayList();
            groupA.forEach(ga -> {
                AtomicReference<Double> total = new AtomicReference<>(0.0);
                WcGroupNum groupNum = wcGroupNumMap.get(ga);
                sourceMap.put(ga, groupNum.getGroupNum5());
                double source = groupNum.getGroupNum5() * groupNum.getGroupNum6() * 3;
                total.updateAndGet(v -> v + groupNum.getGroupNum1());
                total.updateAndGet(v -> v + groupNum.getGroupNum2());
                total.updateAndGet(v -> v + groupNum.getGroupNum3());
                total.updateAndGet(v -> v + groupNum.getGroupNum7());
                total.updateAndGet(v -> v + source);
                groupANum2.add(total.get());
            });

            StringBuilder sb = new StringBuilder();
            String str = WorldCupUtils.getInstance().getByGroup("队 进16强", groupName, groupA, eventA, groupANum2);
            String[] split = str.split("\\n");
            for (String p : split) {
                String newValue = p.split("概率：")[1].trim();
                String pName = p.split("队")[0].trim();
                if (params.containsKey(pName) && sourceMap.containsKey(pName)) {
                    int source = sourceMap.get(pName).intValue();
                    String oldValue = params.get(pName);
                    double newV = Double.parseDouble(newValue.replace("%", ""));
                    double oldV = Double.parseDouble(oldValue.replace("%", ""));
                    sb.append(pName).append("队 (当前积分： ").append(source).append(" )\n初始概率：").append(String.format("%.2f", oldV)).append("%");
                    String tag = "↑ ";
                    double dV = newV - oldV;
                    if (dV < 0) {
                        tag = "↓ ";
                    }
                    sb.append("\n当前概率：").append(String.format("%.2f", newV)).append("%");
                    sb.append("(").append(tag).append(String.format("%.2f", Math.abs(dV))).append("%)");
                }
                sb.append("\n\n");
            }
            sb.append("声明：数据采用ID3决策树算法，仅供参考，不保证完全正确\n未经过允许不得转载，如有疑问可联系作者：dullwolf");
            WxCmdUtil.sendMsg(wxId,sb.toString());
        }

    }

}
